03. For 循环
For 循环
在 Python 中,我们可以使用列表来存储数据序列,并使用 for 循环来遍历列表。下面的代码中包含一个循环,可以将列表中每个名字的首字母大写(将字符串的首字母大写可以通过字符串的 title() 方法来实现),并打印:
names = ['charlotte hippopotamus turner', 'oliver st. john-mollusc',
'nigel incubator-jones', 'philip diplodocus mallory']
for name in names:
print(name.title())
运行该代码可输出:
Charlotte Hippopotamus Turner
Oliver St. John-Mollusc
Nigel Incubator-Jones
Philip Diplodocus Mallory
现在我们来具体看看 for 循环的语法:

-
关键字
for
表示这是一个 for 循环。 -
该行的其余部分表示正在迭代的内容。
names
是这个 for 循环迭代的列表。name
是该循环的迭代变量。针对names
中的每个元素, for 循环的主体都会被执行一次,迭代变量name
可用于循环体,从而指代循环当前处理的元素。 - for 循环的主体部分需要缩进四个空格,并针对列表中的每个元素执行一次。
关于命名的注释
:你可以采用自己喜欢的任何方式命名迭代变量。但是上面这个例子展现了一个常见模式,即列表
names
的名称是以 "s" 结尾的复数,而迭代变量是没有 "s" 的单数。以此模式命名列表和迭代变量,可以使其他程序员更轻松地了解不同的变量。
练习:列表的总和
请在下面的练习中定义一个函数
list_sum
,该函数将一个列表作为参数,并返回列表中元素的总和。你可以使用 for 循环迭代列表。
Start Quiz:
def list_sum(input_list):
sum = 0
# todo: Write a for loop that adds the elements
# of input_list to the sum variable
return sum
#These test cases check that list_sum works correctly
test1 = list_sum([1, 2, 3])
print("expected result: 6, actual result: {}".format(test1))
test2 = list_sum([-1, 0, 1])
print("expected result: 0, actual result: {}".format(test2))
练习:XML 标签计数器
请在下面的练习中编写函数
tag_count
,其参数以字符串列表的形式列出。该函数应该返回字符串中有多少个
XML 标签
。XML 是类似于 HTML 的数据语言,它以左尖括号 "<" 开始,以右尖括号 ">" 结尾。你可以通过检查列表中的字符串是否以 "<" 开始,以 ">" 结尾来判断它是否为 XML 标签。
你可以假设作为输入的字符串列表不包含空字符串。
Start Quiz:
"""Write a function, `tag_count`, that takes as its argument a list
of strings. It should return a count of how many of those strings
are XML tags. You can tell if a string is an XML tag if it begins
with a left angle bracket "<" and ends with a right angle bracket ">".
"""
#TODO: Define the tag_count function
def tag_count(list1):
# Your code goes here!
return count
# Test for the tag_count function:
list1 = ['<greeting>', 'Hello World!', '</greeting>']
count = tag_count(list1)
print("Expected result: 2, Actual result: {}".format(count))
使用循环构建列表
除了利用循环从列表中提取信息之外,我们还可以使用 for 循环创建和修改列表。以我们在这一节开头看到的名单列表为例(注意所有首字母均为小写):
names = ['charlotte hidppopotamus turner', 'oliver st. john-mollusc',
'nigel incubator-jones', 'philip diplodocus mallory']
通过下面的代码,我们可以使用循环生成一个首字母大写的名单:
# create a new list of capitalized names without modifying the original list
capitalized_names = [] #create a new, empty list
for name in names:
capitalized_names.append(name.title()) #add elements to the new list
如果你不想保留首字母小写的名单列表,你也可以将其覆盖,而不是创建一个新列表。
# modify the names list in place
for index in range(len(names)): # iterate over the index numbers of the names list
names[index] = names[index].title() # modify each element of names
如需创建一个新列表,可以从一个空列表 (
[]
) 开始,然后使用
append
方法添加新元素。修改列表更复杂一些,需要使用一个新的函数:
range
。
range
函数需要一个参数,即整数 n,并返回一个从零到 n-1 的数字序列。
>>> for number in range(4):
>>> print(number)
0
1
2
3
使用 range 函数为名单列表中的每个值生成索引。这样我们可以使用
names[index]
访问列表的元素,以便更新
names
列表中的值。
Why
range
?
SOLUTION:
代码没有任何作用练习:创建 HTML 列表
请在下面的练习中编写
html_list
函数。该函数需要一个参数,即一个字符串列表,并返回一个 HTML 列表形式的单个字符串。例如,如果为函数提供列表
['first string', 'second string']
作为参数,则该函数将返回以下字符串。
<ul>
<li>first string</li>
<li>second string</li>
</ul>
也就是说,字符串的第一行应该是开始标签
<ul>
。继第一行之后是源列表中的两个元素(各占一行),前后带有
<li>
和
</li>
标签。字符串的最后一行应该是结束标签
</ul>
。
Start Quiz:
#define the html_list function
def html_list(list_of_strings):
# Your code goes here!
return
print(html_list(['First element', 'Second element', 'Third element']))
range
函数的其他应用
虽然
range
可以用于修改列表,但这并不是它的唯一用处。我们也可以使用该函数将某个操作重复一定次数。
>>> for i in range(3):
... print("Camelot!")
...
Camelot!
Camelot!
Camelot!
>>> print("It's only a model.")
It's only a model.
练习:Starbox
在下面的练习中,
starbox
函数将打印出一个由星号组成的框。该函数有两个参数,即宽度和高度,其单位为字符数量。
这个函数并不完整,尽管它打印了正确宽度的框,但忽略了参数高度。现在请你将函数补充完整,以便根据我们提供的两个测试用例打印出正确大小的框。
提示:
在这个练习中,
range
函数也许可以派上用场!
Start Quiz:
def starbox(width, height):
"""print a box made up of asterisks.
width: width of box in characters, must be at least 2
height: height of box in lines, must be at least 2
"""
print("*" * width) #print top edge of box
# print sides of box
# todo: print this line height-2 times, instead of three times
print("*" + " " * (width-2) + "*")
print("*" + " " * (width-2) + "*")
print("*" + " " * (width-2) + "*")
print("*" * width) #print bottom edge of box
# Test Cases
print("Test 1:")
starbox(5, 5) # this prints correctly
print("Test 2:")
starbox(2, 3) # this currently prints two lines too tall - fix it!
单击“下一项”查看该练习的解决方案。